package com.example.agent;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class SimpleAgent {

    public static void premain(String options, Instrumentation inst) {
        // 打印参数
        System.out.println("premain, options: " + options + ", inst: " + inst.toString());
        // 第二个参数canRetransform参数指定是否允许对已经加载的类进行重新转换，不传默认false
        inst.addTransformer(new SimpleTransformer());
    }

    static class SimpleTransformer implements ClassFileTransformer {
        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                                ProtectionDomain protectionDomain, byte[] classfileBuffer) {
            // 打印所有参数
            System.out.println("loader: " + loader + ", className: " + className + ", classBeingRedefined: " + classBeingRedefined + ", protectionDomain: " + protectionDomain + ", classfileBuffer: " + classfileBuffer.length);
            // 返回原字节码
            return classfileBuffer;
        }
    }
}
